package server.handler;
import com.sun.net.httpserver.*;
import jdk.nashorn.internal.parser.JSONParser;
import jdk.nashorn.internal.runtime.JSONFunctions;
import netscape.javascript.JSObject;
import org.json.JSONArray;
import org.json.JSONObject;

import server.database.*;
import server.entity.Coordinate;


import javax.print.attribute.HashAttributeSet;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.SQLException;
import java.time.*;
import java.time.format.DateTimeFormatter;


public class CoordinateHandler implements HttpHandler  {
    private CoordDatabase db;
    private Integer maxDataLen = 1024;
    public CoordinateHandler() {
        db = CoordDatabase.getInstance();
    }

    @Override
    public void handle(HttpExchange exchange) throws IOException {
        Headers headers = exchange.getRequestHeaders();
        String contentType = headers.get("Content-Type").get(0);
        if(contentType.equalsIgnoreCase("application/json")){
            if (exchange.getRequestMethod().equalsIgnoreCase("GET")) {
                System.out.println(888888);
                //login check
//                if(!Handler.authentication(exchange)){
//                    Handler.errorHandler(exchange, "Please login or register first");
//                    return;
//                }
                JSONArray allCoordinates;
                try{
                    allCoordinates = db.getAllCoordinates();
                } catch (SQLException e){
                    Handler.errorHandler(exchange, e);
                    return;
                }
               Handler.sendResponse(exchange, allCoordinates);

            } else if (exchange.getRequestMethod().equalsIgnoreCase("POST")) {
//                if(!Handler.authentication(exchange)){
//                    Handler.errorHandler(exchange, "Please login or register first");
//                    return;
//                }
                String inputData;
                try{
                    inputData = Handler.getRequestData(exchange);
                }catch (IOException e){
                    Handler.errorHandler(exchange, e);
                    return;
                }

                JSONObject jsonObject = new JSONObject(inputData);
                //attribute validation
                if(!jsonObject.has("sent")){
                    Handler.errorHandler(exchange, "sent time is required");
                    return;
                }
                else if(!jsonObject.has("username")){
                    Handler.errorHandler(exchange, "username is required");
                    return;
                }
                else if(!jsonObject.has("latitude")){
                    Handler.errorHandler(exchange, "latitude is required");
                    return;
                }
                else if(!jsonObject.has("longitude")){
                    Handler.errorHandler(exchange, "longitude is required");
                    return;
                }
                if(!jsonObject.has("description") || jsonObject.get("description").equals("")){
                    jsonObject.put("description", "nodata");
                }
                //save coordinate
                String time = jsonObject.getString("sent");
                LocalDateTime date;
                try{
                    date = Handler.localDateTimeToEpochMilli(time);
                }catch (Exception e){
                    Handler.errorHandler(exchange, e);
                    return;
                }
                //时间类型转时间戳类型
                Coordinate coordinate = new Coordinate(date,
                        jsonObject.getString("username"),
                        jsonObject.getDouble("latitude"),
                        jsonObject.getDouble("longitude"));

                if(jsonObject.has("description"))coordinate.setDescription(jsonObject.getString("description"));
                System.out.println(coordinate);
                try {
                    db.storeCoordinates(coordinate);
                } catch (SQLException e) {
                    Handler.errorHandler(exchange, e);
                    return;
                }
                Handler.sendResponse(exchange, "success");

            }else{
                //Code for handling other requests
                Handler.errorHandler(exchange, "Unsupported request method");
            }
        }else{
            Handler.errorHandler(exchange, "Unsupported request contentType");
        }
    }
}
